﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Diagnostics;
using LevSTProgramTransform.RxTxPacketUtilitys;
using System.Timers;
using LevSTProgramTransform.Properties;

namespace LevSTProgramTransform
{
    public partial class SerialPortControlPanel : Form
    {
        private Settings settings = Settings.Default;

        private System.Timers.Timer aTimer;
        private const int IntervalTimeMs = 6000;   //6000 ms
        #region Local Variables
        string[] gBaudRateItems = { "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200" };
        string gDefaultBaudRate = "9600";
        string[] gDataBitsItems = { "7", "8", "9" };
        string gDefaultDataBits = "8";
        string gDefaultParity = "None";
        string gDefaultStopBits = "One";
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error, Dummy };
        // Various colors for logging info
        private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red, Color.Pink };
        List<Byte> ReceivedComPortBytesList = new List<Byte>();
        List<Byte> TrasnmitComPortBytesList = new List<Byte>();
        #endregion

        bool gControlPanelEnable = true;
        AutoDetectingComPorts gADCP;
        private Dictionary<string, string> gSerialPorts;

        private SerialPort gSerialComPort = new SerialPort();

        bool gWaitReceiveData = false;
        bool gGetStatusReceiveData = false;
        bool gGetEEPROMReceiveData = false;
        ReceiveDataTransform RDTrans;
        private string HexPath;
        private string PRGHexFile;
        private string ROMHexFile;

        public SerialPortControlPanel()
        {
            InitializeComponent();

            //DialogResult result = MessageBox.Show("UseAutoDetection", "Confirmation", MessageBoxButtons.YesNoCancel);
            //if (result == DialogResult.Yes)
            //{
            //    this.Close();
            //}
            //else if (result == DialogResult.No)
            //{
            //}
            //else
            //{
            //}
        }

        private void SerialPortControlPanel_Load(object sender, EventArgs e)
        {

            StartPosition = FormStartPosition.CenterScreen;
            InitializeControlValues();
            gADCP = new AutoDetectingComPorts();
            gADCP.ComPortChangeEventHandler += new EventHandler(ComPortChangeEvent);   // 訂閱(subscribe) 事件 
            //setPortNameItems(AutoDetectingComPorts.getComPortItems(gADCP.SerialPorts));
            cmbPortName.Items.Clear();
            changeCombeBoxItems(gADCP.SerialPorts, cmbPortName);


            // Create a timer with a ten second interval. ms
            aTimer = new System.Timers.Timer(10000);
            // Set the Interval to 6 seconds (6000 milliseconds).
            aTimer.Interval = IntervalTimeMs;
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        }

        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
            cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
            cmbStopBits.Text = gDefaultStopBits;
            cmbDataBits.Text = gDefaultDataBits;
            cmbParity.Text = gDefaultParity;
            cmbBaudRate.Text = gDefaultBaudRate;
            setPanelEnable(true);

            cmbParity.Enabled = false;
            cmbStopBits.Enabled = false;
            cmbDataBits.Enabled = false;
            cmbBaudRate.Enabled = false;

            getOneWireData_button.Enabled = false;

            UpdateLabelUI("Result", Color.LightGray, Result_label);
        }
        public void setPanelEnable(bool enable)
        {
                gControlPanelEnable = enable;
                serialPortPanel.Enabled = enable;
        }
        public void setPortNameItems(string[] items)
        {
            cmbPortName.Items.Clear();
            cmbPortName.Items.AddRange(items);
        }
        private void changeCombeBoxItems(Dictionary<string, string> dict, ComboBox cmb)
        {
            string select;
            gSerialPorts = dict;
            if (!gControlPanelEnable)
            {
                return;
            }
            if (dict.Count <= 0)
            {
                cmbPortName.Items.Clear();
                return;
            }
            if (cmb.Text == string.Empty)
            {
                select = "";
            }
            else
            {
                select = cmb.Text;
            }

            cmb.Items.Clear();
            cmb.Items.AddRange(AutoDetectingComPorts.getComPortItems(dict));
            if (AutoDetectingComPorts.FindingComPortName(select, dict) == string.Empty)
            {
                cmb.SelectedIndex = 0;
                return;
            }
            else
            {
                cmb.Text = select;
            }
        }
        public Panel getControlPanel()
        {
            return serialPortPanel;
        }
        //// The method that implements the delegated functionality  
        //事件處理方法
        private void ComPortChangeEvent(Object sender, EventArgs e)
        {
            // 判斷物件是否為 ComPortStatusUpdate_EventArgs 實體
            if (e is ComPortChangeEventHandlerArgs)
            {
                // 將物件由 EventArgs 轉型 ComPortStatusUpdate_EventArgs
                ComPortChangeEventHandlerArgs msg = e as ComPortChangeEventHandlerArgs;
                if ((msg.ChangeEventType == ComPortChangeEventType.ComPortAttachedEvent) ||
                    (msg.ChangeEventType == ComPortChangeEventType.ComPortRemovedEvent))
                {
                    gSerialPorts = msg.DictMessage;

                    UpdateComboBoxUI(gSerialPorts, cmbPortName);
                }
                //CheckAndConnectionWithDevices(dict);

                //// When you use foreach to enumerate dictionary elements,
                //// the elements are retrieved as KeyValuePair objects.
                //foreach (KeyValuePair<string, string> kvp in dict)
                //{
                //    string str = string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                //    //Log(LogMsgType.Incoming, str + Environment.NewLine);
                //}
            }
        }

        private delegate void ComboBoxUICallBack(Dictionary<string, string> dict, Control combeBox);
        private void UpdateComboBoxUI(Dictionary<string, string> dict, Control ctl)
        {
            if (this.InvokeRequired)
            {
                ComboBoxUICallBack myUpdate = new ComboBoxUICallBack(UpdateComboBoxUI);
                this.Invoke(myUpdate, dict, ctl);
            }
            else
            {
                // 判斷物件是否為 ComboBox 實體
                if (ctl is ComboBox)
                {
                    // 將物件由 EventArgs 轉型 ComboBox
                    ComboBox cmb = ctl as ComboBox;
                    changeCombeBoxItems(dict, cmb);
                }
            }
        }
        private delegate void LabelUICallBack(string str, Color c, Control ctl);
        public void UpdateLabelUI(string str, Color c, Control ctl)
        {
            if (this.InvokeRequired)
            {
                LabelUICallBack myUpdate = new LabelUICallBack(UpdateLabelUI);
                this.Invoke(myUpdate, str, c, ctl);
            }
            else
            {
                // 判斷物件是否為 Label 實體
                if (ctl is Label)
                {
                    // 將物件由 EventArgs 轉型 Label
                    Label lab = ctl as Label;
                    lab.Text = str;
                    lab.BackColor = c;
                }
            }
        }
        #region FormInvokFunctions
        /// <summary> Log data to the terminal window. </summary>
        /// <param name="msgtype"> The type of message to be written. </param>
        /// <param name="msg"> The string containing the message to be shown. </param>
        private void Log_Clear()
        {
            inform_richTextBox.Invoke(new EventHandler(delegate
            {
                inform_richTextBox.Clear ();
            }));
        }
        private void Log(LogMsgType msgtype, string msg)
        {
                inform_richTextBox.Invoke(new EventHandler(delegate
                {
                    inform_richTextBox.SelectedText = string.Empty;
                    inform_richTextBox.SelectionFont = new Font(inform_richTextBox.SelectionFont, FontStyle.Bold);
                    inform_richTextBox.SelectionColor = LogMsgTypeColor[(int)msgtype];
                    inform_richTextBox.AppendText(msg);
                    inform_richTextBox.ScrollToCaret();
                }));
        }



        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetTextCallback(string text);
        public void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.

            //if (this.Infor_richTextBox.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            //else
            {
                //this.Infor_richTextBox.AppendText(text);
                Log(LogMsgType.Normal, text);
            }
        }

        private delegate void myUICallBack(string myStr, Control ctl, Color back_clor);
        private void UpdateMyUI(string myStr, Control ctl, Color back_clor)
        {
            if (this.InvokeRequired)
            {
                myUICallBack myUpdate = new myUICallBack(UpdateMyUI);
                this.Invoke(myUpdate, myStr, ctl, back_clor);
            }
            else
            {
                ctl.Text = myStr;
                ctl.BackColor = back_clor;
            }
        }
        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetFunctionStatusCallback(bool flag);
        public void SetFunctionStatus(bool flag)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.InvokeRequired)
            {
                SetFunctionStatusCallback statusUpdate = new SetFunctionStatusCallback(SetFunctionStatus);
                this.Invoke(statusUpdate, flag);//, ctl);
            }
            else
            {
                //show_communication_status(flag);
            }
        }
        #endregion

        public void SerialPortOpen()
        {
            try
            {
                // Set the port's settings
                gSerialComPort.BaudRate = int.Parse(cmbBaudRate.Text);
                gSerialComPort.DataBits = int.Parse(cmbDataBits.Text);
                gSerialComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                gSerialComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                gSerialComPort.PortName = AutoDetectingComPorts.FindingComPortName(cmbPortName.Text, gSerialPorts);
                gSerialComPort.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Can not open Serial Port : " + gSerialComPort.PortName + Environment.NewLine + Environment.NewLine +
                    ex.ToString());
            }
        }
        public void SerialPortClose()
        {
            if (gSerialComPort.IsOpen)
            {
                Application.DoEvents();
                gSerialComPort.DiscardInBuffer();
                gSerialComPort.DiscardOutBuffer();
                MassUtilityClass.PauseForMilliSeconds(1000);
                Application.DoEvents();
            }
            gSerialComPort.Close();
        }

         private void SerialPortControlPanel_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (gADCP != null)
            {
                gADCP.StopDetection();
            }
            SerialPortClose();
            aTimer.Enabled = false;
            aTimer.Dispose();
        }

        private void OpenPort_button_Click(object sender, EventArgs e)
        {
            //if(!(System.IO.File.Exists(Path.Combine(HexPath, PRGHexFile))&&System.IO.File.Exists(Path.Combine(HexPath, ROMHexFile)))){
            //    MessageBox.Show( "PRG, ROM HEX Files setting fail....", "Failure.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}


            if (!gSerialComPort.IsOpen)
            {
                SerialPortOpen();
                if (gSerialComPort.IsOpen)
                {
                    gSerialComPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
                    OpenPort_button.Text = "Close Port";
                                       
                    Log(LogMsgType.Warning,"Serial Port has been opened....." + Environment.NewLine + Environment.NewLine);
                    setPanelEnable(false);
                    //getOneWireData_button.Enabled = true;
                    SelectBurningFiles_groupBox2.Enabled = true;
                }
            }
            else
            {
                // If the port is open, close it.
                if (gSerialComPort.IsOpen)
                {
                    //MessageBox.Show("Wait for Closing Serial Com Port.... " + Environment.NewLine);
                    //Display f as a modeless dialog
                    //MessageForm f = new MessageForm();
                    //f.setMessage("Wait for Closing Serial Com Port.... " + Environment.NewLine, "");
                    //f.Show();
                    Log(LogMsgType.Warning,"Wait for Closing Serial Com Port.... " + Environment.NewLine);
                    SerialPortClose();
                    //f.setMessage("Already Closed Serial Com Port." + Environment.NewLine, "");
                    if (!gSerialComPort.IsOpen)
                    {
                        gSerialComPort.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
                        OpenPort_button.Text = "Open Port";
                        Log(LogMsgType.Warning,"Already Closed Serial Com Port." + Environment.NewLine + Environment.NewLine);
                        setPanelEnable(true);
                        getOneWireData_button.Enabled = false;
                        SelectBurningFiles_groupBox2.Enabled = false;
                        UpdateLabelUI("Result", Color.LightGray, Result_label);
                        ResetSelectFileGroupBox();
                    }
                }
            }
            // Load user settings
            //settings.Reload();
            //Log(LogMsgType.Warning,"setting." + settings.PreviousSelectDirectory + Environment.NewLine + Environment.NewLine);
        }
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // If the com port has been closed, do nothing
            if (!gSerialComPort.IsOpen) return;

                // Obtain the number of bytes waiting in the port's buffer
                int readbytes = gSerialComPort.BytesToRead;
                if (readbytes > 0)
                {
                    // Create a byte array buffer to hold the incoming data
                    byte[] buffer = new byte[readbytes];
                    // Read the data from the port and store it in our buffer
                    gSerialComPort.Read(buffer, 0, readbytes);
                    //Log(LogMsgType.Dummy, "RAW Data: " + MassUtilityClass.ByteArrayToHexString(buffer));
                    //Log(LogMsgType.Dummy, "{receive bytes: " + buffer.Length + "}" + Environment.NewLine);

                    ReceivedComPortBytesList.AddRange(buffer);


                    List<LEV_One_Wire_Receiving_Packet_Decoding.Received_Data_Group> outDataGroupList;
                    List<byte[]> outDataList;
                    LEV_One_Wire_Receiving_Packet_Decoding.Packet_Decoding_To_Group_And_Clear_List(
                        ref ReceivedComPortBytesList, out outDataGroupList, out outDataList);
                    if ((outDataGroupList.Count >= 1) && (outDataGroupList.Count == outDataList.Count))
                    {
                        for (int i = 0; i < outDataGroupList.Count; i++)
                        {
                            if (outDataGroupList[i] == LEV_One_Wire_Receiving_Packet_Decoding.Received_Data_Group.OneWire_SystemData_Group)
                            {
                                Log(LogMsgType.Incoming, "Receiving OneWire_SystemData_Group: " +
                                MassUtilityClass.ByteArrayToHexString(outDataList[i], true) + Environment.NewLine);
                                if (gWaitReceiveData)
                                {
                                    gGetStatusReceiveData = true;
                                    RDTrans.setOneWire_SystemData(outDataList[i]);
                                }
                            }
                            else if (outDataGroupList[i] == LEV_One_Wire_Receiving_Packet_Decoding.Received_Data_Group.OneWire_EEPROM_Group)
                            {
                                Log(LogMsgType.Incoming, "Receiving OneWire_EEPROM_Group: " +
                                MassUtilityClass.ByteArrayToHexString(outDataList[i], true) + Environment.NewLine);
                                if (gWaitReceiveData)
                                {
                                    gGetEEPROMReceiveData = true;
                                    RDTrans.setOneWire_EEPROM(outDataList[i]);
                                } 
                            }
                            else
                            {
                                //Log(LogMsgType.Error, "[Fail] None OneWire_Data : " + outDataGroupList[i] + Environment.NewLine);
                                //Log(LogMsgType.Error, "Group data : " + MassUtilityClass.ByteArrayToHexString(outDataList[i]) + Environment.NewLine);
                            }
                        }
                        if (gGetEEPROMReceiveData && gGetStatusReceiveData)
                        {
                            aTimer.Enabled = false;
                            gWaitReceiveData = false;
                            gGetEEPROMReceiveData = false;
                            gGetStatusReceiveData = false;
                            //RDTransForm.Show(this);
                            bool flag = RDTrans.Transforming();
                            if (flag)
                            {
                                UpdateLabelUI("Success", Color.LightGreen, Result_label);
                                MessageBox.Show("BarCodeID :" + Environment.NewLine +
                                    RDTrans.BarCodeID + Environment.NewLine +
                                    "Programming Success.");
                            }
                            else
                            {
                                UpdateLabelUI("Failure", Color.Red, Result_label);
                                MessageBox.Show("BarCodeID :" + Environment.NewLine +
                                    RDTrans.BarCodeID + Environment.NewLine +
                                    "Programming Fail.");
                            }
                        }
                    }
                }
        }

        private bool sendLevCmd(byte cmd, byte[] values)
        {
            byte[] TransmitData = LEV_UART_Packet_Forming_and_Decoding.CMD_Forming_For_Transmitting(cmd, values);
            if (gSerialComPort.IsOpen)
            {
                Log(LogMsgType.Outgoing, "Transmitting: " + MassUtilityClass.ByteArrayToHexString(TransmitData, true) + Environment.NewLine);
                // Send the binary data out the port
                gSerialComPort.Write(TransmitData, 0, TransmitData.Length);
                return true;
            }
            else
            {
                Log(LogMsgType.Error, "Could not Transmit data: " + MassUtilityClass.ByteArrayToHexString(TransmitData, true) + Environment.NewLine);
                return false;
            }
        }
        private void getOneWireData_button_Click(object sender, EventArgs e)
        {
            UpdateLabelUI("Starting", Color.LightSkyBlue, Result_label);
            gWaitReceiveData = true;
            gGetStatusReceiveData = false;
            gGetEEPROMReceiveData = false;
            RDTrans = new ReceiveDataTransform(PRGHexFile, ROMHexFile, HexPath);

            bool flag = sendLevCmd(0xb2, new byte[]{0x01});
            if (flag)
            {
                aTimer.Enabled = true;
                aTimer.Interval = IntervalTimeMs;
            }
            else
            {
                aTimer.Enabled = false;
                UpdateLabelUI("Error", Color.Red, Result_label);
            }
        }
        // Specify what you want to happen when the Elapsed event is 
        // raised.
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            UpdateLabelUI("Error", Color.Red, Result_label);
            gWaitReceiveData = false;
            gGetStatusReceiveData = false;
            gGetEEPROMReceiveData = false;
            aTimer.Enabled = false;
            MessageBox.Show("Please Retry" + Environment.NewLine + "System has not been received Correct Data for a while ....", "Receiving Timer", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void PRG_Select_button_Click(object sender, EventArgs e)
        {
//            OpenFileDialog openFileDialog_1;
//            openFileDialog_1 = new OpenFileDialog();
//            openFileDialog1.InitialDirectory = @"c:\MyFolder\Default\"; // 檔案對話方框開啟的預設資料夾
//2
//// 設定可以選擇的檔案類型
//3
//openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Comma-Delimited Files (*.csv)|*.csv|All Files (*.*)|*.*";
//4
//openFIleDialog1.CheckFileExists = true;             // 若檔案/路徑 不存在是否顯示錯誤訊息
//5
//openFIleDialog1.CheckPathExists = false;
//6
//DialogResult result = openFileDialog1.ShowDialog();     // 顯示檔案對話方框並回傳狀態（DialogResult.OK、DialogResult.Cancel）
//7
//if (result == DialogResult.OK) {
//8
//    // 操作檔案 openFileDialog1.FileName
//9
//}

        }

        private void LoadFiles_button_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog_1;
            openFileDialog_1 = new OpenFileDialog();
            if (string.IsNullOrEmpty(settings.PreviousSelectDirectory) || (!System.IO.Directory.Exists(settings.PreviousSelectDirectory)))
            {
                //獲得桌面路徑
                string filder = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                openFileDialog_1.InitialDirectory = filder; // 檔案對話方框開啟的預設資料夾
            }
            else
            {
                openFileDialog_1.InitialDirectory = settings.PreviousSelectDirectory; // 檔案對話方框開啟的預設資料夾
            }

            // 設定可以選擇的檔案類型
            openFileDialog_1.Filter = "xml setting Files (*.xml)|*.xml";
            //openFileDialog_1.Filter = "Text Files (*.txt)|*.txt|Comma-Delimited Files (*.csv)|*.csv|All Files (*.*)|*.*";
            openFileDialog_1.CheckFileExists = true;             // 若檔案/路徑 不存在是否顯示錯誤訊息
            openFileDialog_1.CheckPathExists = false;             // 若檔案/路徑 不存在是否顯示錯誤訊息
            DialogResult result = openFileDialog_1.ShowDialog();     // 顯示檔案對話方框並回傳狀態（DialogResult.OK、DialogResult.Cancel）
            if (result == DialogResult.OK)
            {
                // 操作檔案 
                string fullfilename = openFileDialog_1.FileName;
                //Log(LogMsgType.Normal, "Select Full File Name: " + fullfilename + Environment.NewLine);
                Log(LogMsgType.Normal, "Select Directory Name: " + Environment.NewLine + Path.GetDirectoryName(fullfilename) + Path.DirectorySeparatorChar + Environment.NewLine);
                Log(LogMsgType.Normal, "Select File Name: " + Environment.NewLine + Path.GetFileName(fullfilename) + Environment.NewLine);
                if (checkAndSetPRGParameter(fullfilename))
                {
                    settings.PreviousSelectDirectory = Path.GetDirectoryName(fullfilename);
                    settings.PreviousSelectSettingFile = Path.GetFileName(fullfilename);
                    settings.Save();
                    getOneWireData_button.Enabled = true;
                    Log(LogMsgType.Incoming, "Setting Success. " + Environment.NewLine);
                }
                else
                {
                    getOneWireData_button.Enabled = false;
                    Log(LogMsgType.Error, "Setting Failure. " + Environment.NewLine);
                }
                //string fileDirectory = Path.GetDirectoryName(fullfilename);
                //string filename = Path.GetFileName(fullfilename);
                //Log(LogMsgType.Incoming, "fileDirectory: " + fileDirectory + Environment.NewLine);
                //Log(LogMsgType.Incoming, "fileName: " + filename + Environment.NewLine);
            }
        }
        private bool checkAndSetPRGParameter(string fullFileName)
        {
            bool flag = false;
            try
            {
                TemplateFileSetting tfs = new TemplateFileSetting(fullFileName);
                if (!tfs.isCorrectSettingFile()) throw new Exception("it does not correct setting file. ");//return false;

                HexPath = tfs.getHexDirectory();
                PRGHexFile = tfs.getPRGName();
                ROMHexFile = tfs.getRomName();
                if (!System.IO.File.Exists(Path.Combine(HexPath, PRGHexFile)))
                {
                    MessageBox.Show("PRG HEX File does not exists....", "Failure.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("PRG HEX File does not exists....");  //return false;
                }
                if (!System.IO.File.Exists(Path.Combine(HexPath, ROMHexFile)))
                {
                    MessageBox.Show("ROM HEX File does not exists....", "Failure.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("ROM HEX File does not exists....");  //return false;
                }
                //if (!(System.IO.File.Exists(Path.Combine(HexPath, PRGHexFile)) && System.IO.File.Exists(Path.Combine(HexPath, ROMHexFile))))
                //{
                //    MessageBox.Show("PRG, ROM HEX Files setting fail....", "Failure.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //    return;
                //}
                ProjectName_label.Text = tfs.getPrjectName();
                Version_label.Text = tfs.getPrjectVersion();
                BuildDate_label.Text = tfs.getBuildDate();
                BuildTime_label.Text = tfs.getBuildTime();
                this.FW_PRGHEX_label.Text = PRGHexFile;
                this.FW_ROMHEX_label.Text = ROMHexFile;
                return true;
            }
            catch
            {
                flag = false;
            }
            ResetSelectFileGroupBox();
            return flag;
        }
        void ResetSelectFileGroupBox()
        {
            string failStr = "None";
            ProjectName_label.Text = failStr;
            Version_label.Text = failStr;
            BuildDate_label.Text = failStr;
            BuildTime_label.Text = failStr;
            this.FW_PRGHEX_label.Text = failStr;
            this.FW_ROMHEX_label.Text = failStr;
        }
    }//Class SerialPortControlPanel
}//namespace LevSTProgramTransform
